package simorg.domain;

import java.text.SimpleDateFormat;
import java.util.Collection;
import java.util.Date;

import org.dom4j.Element;

import simorg.domain.persistence.CompoundAssignmentJoinTable;
import simorg.domain.persistence.CourseTable;
import simorg.util.DatabaseConnection;
import simorg.util.StringUtil;

public class Assignment {

	private int id;
	private String title;
	private Date assignedDate;
	private Date dueDate;
	private int numCompoundsToComplete;
	private int courseId;
	
	private Course course; // lazy load.
	
	public static final SimpleDateFormat dateFormatter = new SimpleDateFormat("MM/dd/yyyy");
	
	public Assignment() {
		this.id = -1;
	}

	public void buildDomainXml(Element root, DatabaseConnection dc) {
		Element assignment = root.addElement("assignment");
		assignment.addAttribute("id", String.valueOf(this.getId()));
		Element title = assignment.addElement("title");
		title.setText(StringUtil.nullSafe(this.getTitle()));
		
		Element assignedDate = assignment.addElement("assignedDate");
		assignedDate.setText(dateFormatter.format(this.getAssignedDate()));
		Element dueDate = assignment.addElement("dueDate");
		dueDate.setText(dateFormatter.format(this.getDueDate()));
		Element numCompoundsToComplete = assignment.addElement("numCompoundsToComplete");
		numCompoundsToComplete.setText(String.valueOf(this.getNumCompoundsToComplete()));
		Element courseId = assignment.addElement("courseId");
		courseId.setText(String.valueOf(this.getCourseId()));
		Collection<Compound> compound = this.getAssignedCompounds(dc);
		if ( compound != null) {
			Element assignedCompoundsElement = assignment.addElement("assignedCompounds");
			for (Compound c : compound ) {
				c.buildDomainXml(assignedCompoundsElement);
			}
		}
		return;
	}
	
	public int getId() {
		return id;
	}

	public void setId(int id) {
		this.id = id;
	}

	public String getTitle() {
		return title;
	}

	public void setTitle(String title) {
		this.title = title;
	}

	public Date getAssignedDate() {
		return assignedDate;
	}

	public void setAssignedDate(Date assignedDate) {
		this.assignedDate = assignedDate;
	}

	public Date getDueDate() {
		return dueDate;
	}

	public void setDueDate(Date dueDate) {
		this.dueDate = dueDate;
	}

	public int getNumCompoundsToComplete() {
		return numCompoundsToComplete;
	}

	public void setNumCompoundsToComplete(int numCompoundsToComplete) {
		this.numCompoundsToComplete = numCompoundsToComplete;
	}

	public int getCourseId() {
		return courseId;
	}

	public void setCourseId(int courseId) {
		this.courseId = courseId;
	}

	public Course getCourse(DatabaseConnection db) {
		if ( this.course == null ) {
			this.course = CourseTable.findById(db, this.courseId);
		}
		return course;
	}
	
	
	public Collection<Compound> getAssignedCompounds(DatabaseConnection dc) {
		return CompoundAssignmentJoinTable.findCompoundsByAssignment(dc, this.getId());
	}
}
